﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Xpus.YouYTube.Utility;
using Xpus.YouYTube.Data;
using System.Net.Json;

namespace Xpus.YouYTube.WebSite.Controllers
{
	public class CommentController : Controller
	{
		public void CommentSubmit(string svideoId, string userName, string body,
			string recaptcha_challenge_field, string recaptcha_response_field)
		{
			try
			{
				int videoId = int.Parse(svideoId);
				string ip = Request.UserHostAddress;
				string rawBody = "";

				if (TIpUtility.IsIpBlocked(ip, true))
				{
					Response.Write("F对不起，您的IP地址已被屏蔽！您无法发表评论。");
					return;
				}

				if (body != null)
					rawBody = body.Trim();

				if (rawBody == "")
				{
					Response.Write("F必须填写评论内容");
					return;
				}

				if (!TReCaptcha.Verify(recaptcha_challenge_field, recaptcha_response_field))
				{
					Response.Write("F对不起，验证码错误！");
					return;
				}

				using (TDataContext db = new TDataContext())
				{
					TComment oc = db.TComments.FirstOrDefault(c =>
						c.VideoId == videoId &&
						c.UserIp == ip &&
						c.AddedTime > DateTime.Now.AddSeconds(-30));
					if (oc != null)
					{
						Response.Write("F30秒内不许再次评论，请稍候再试。");
						return;
					}

					TComment comment = new TComment()
					{
						VideoId = videoId,
						UserName = userName == null ? "" : TSensitiveWordManager.Repleace(userName),
						Body = body == null ? "" : TSensitiveWordManager.Repleace(body),
						AddedTime = DateTime.Now,
						IsDeleted = false,
						UserIp = ip,
					};
					db.TComments.InsertOnSubmit(comment);
					db.SubmitChanges();
					Response.Write("T评论发表成功，谢谢！");
				}
			}
			catch (Exception ex)
			{
				Response.Write("F发生未知错误：" + ex.Message);
			}
		}

		public void GetComments(string svideoId, string spageIndex, string spageSize)
		{
			try
			{
				int videoId = int.Parse(svideoId);
				int pageIndex = int.Parse(spageIndex);
				int pageSize = int.Parse(spageSize);
				int totalPages = 0;

				using (TDataContext db = new TDataContext())
				{
					TVideo video = db.TVideos.FirstOrDefault(v => v.Id == videoId && v.IsDeleted == false);

					if (video == null)
					{
						Response.Write("F视频不存在。");
						Response.End();
						return;
					}

					var q = from c in db.TComments
							where c.VideoId == videoId && c.IsDeleted == false
							select c;

					totalPages = (q.Count() + pageSize - 1) / pageSize;

					if (pageIndex < 0)
						pageIndex = totalPages;

					TComment[] comments = q.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToArray();

					JsonObjectCollection json = new JsonObjectCollection();
					json.Add(new JsonNumericValue("PageIndex", pageIndex));
					json.Add(new JsonNumericValue("PageSize", pageSize));
					json.Add(new JsonNumericValue("TotalPages", totalPages));

					JsonArrayCollection cs = new JsonArrayCollection("Comments");
					foreach (var c in comments)
					{
						JsonObjectCollection co = new JsonObjectCollection();
						co.Add(new JsonNumericValue("Id", c.Id));
						co.Add(new JsonStringValue("UserName", HttpUtility.HtmlEncode(c.UserName)));
						co.Add(new JsonStringValue("AddedTime", c.AddedTime.ToString("yyyy-MM-dd HH:mm:ss")));
						co.Add(new JsonStringValue("Body", HttpUtility.HtmlEncode(c.Body).Replace("\r\n", "<br/>")));
						co.Add(new JsonNumericValue("Anumber", c.AgreeNumber));
						co.Add(new JsonNumericValue("Dnumber", c.DisagreeNumber));

						cs.Add(co);
					}
					json.Add(cs);

					Response.Write("T" + json.ToString());
				}
			}
			catch(Exception ex)
			{
				Response.Write("F发生了未知错误：" + ex.Message);
			}
		}
	}
}
